<template>
  <div class="">
    <!--    顶部导航条-->
    <navheader></navheader>
    <div class="main ml-4" style="padding-top:70px">
      <!--    主体内容-->
      <div class="row mt-4 ml-4">
        <!--        左边-->
        <div class="col-md-9 column">
          <div class="row">
            <div class="col-md-12 column">
              <div class="card">
                <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                    <el-menu-item index="1">
                      <router-link to="/Resale/All_Resale">
                        <span class="" style="font-size: 20px">闲置转卖区</span>
                      </router-link>
                    </el-menu-item>
<!--                    <el-menu-item index="2">-->
<!--                      <router-link to="/Resale/My_Resale">-->
<!--                        <span class=""  style="font-size: 20px">我发布的</span>-->
<!--                      </router-link>-->
<!--                    </el-menu-item>-->
                </el-menu>
                <!-- Tab panes -->
                <div class="tab-content" style="height: 1250px">
                  <router-view></router-view>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!--        右边-->
        <div class="col-md-3 column">
          <div class="row">
            <div class="col-md-12 column">
              <div class="card" style="width: 16rem;">
                <div class="mt-5 ml-5 mr-5" style="border-radius:70%; height: 130px; width: 130px;overflow:hidden;">
                  <img class=" card-img-top" :src="this.show_user_img" style="height: 130px;" />
                </div>
                <div class="card-body text-center">

                  <el-tooltip class="item" effect="dark" content="跳转我发布的" placement="right">

                    <a class="card-title "
                       style="font-size: 24px;color: #057a5b;font-weight: bold"
                       @click="change_user"
                       href="javascript:void(0);">
                      {{this.user_info.user_name}}
                    </a>

                  </el-tooltip>
                  <p class="card-text text-center pt-1" v-if="this.user_info.identity==1">学长学姐</p>
                  <p class="card-text text-center pt-1" v-else-if="this.user_info.identity==2">老师</p>
                  <p class="card-text text-center pt-1" v-else-if="this.user_info.identity==0">学生</p>
                  <div class="row pl-3">
                    <el-button type="primary" @click="openSubmit()" round plain>我要发布</el-button>
                    <el-button type="warning" @click="openDeal()" round plain>我的交易</el-button>
                  </div>

                  <el-dialog title="发布闲置物品" :visible.sync="dialogFormVisible" @close="handleClose" width="50%">

                    <el-form :model="form" :rules="rules" :before-close="closeDiv"
                             ref="form"
                             label-width="120px"
                             class="form"
                             status-icon>

                      <el-form-item label="闲置物品名称" :label-width="formLabelWidth" prop="idle_item_name">
                        <el-input v-model="form.idle_item_name"
                                  type="text"
                                  maxlength="20"
                                  autocomplete="off"
                                  show-word-limit
                                  placeholder="请输入闲置物品名，3-20个字符..."></el-input>
                      </el-form-item>

                      <el-row>
                        <el-col :span="10">
                          <el-form-item label="闲置物品类别" :label-width="formLabelWidth" prop="idle_item_category">
                            <el-select v-model="form.idle_item_category" placeholder="选择闲置物品类别...">
                              <el-option label="考研笔记" value="1"></el-option>
                              <el-option label="书籍" value="2"></el-option>
                              <el-option label="文具" value="3"></el-option>
                              <el-option label="考卷" value="4"></el-option>
                              <el-option label="其他" value="5"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>

                        <el-col :span="10">
                          <el-form-item label="科目" :label-width="formLabelWidth" prop="idle_item_subject">
                            <el-select v-model="form.idle_item_subject" placeholder="选择闲置物品科目...">
                              <el-option label="英语" value="1"></el-option>
                              <el-option label="数学" value="2"></el-option>
                              <el-option label="政治" value="3"></el-option>
                              <el-option label="专业" value="4"></el-option>
                              <el-option label="其他" value="5"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>

                      </el-row>

                      <el-row>

                        <el-col :span="10">
                          <el-form-item label="新旧程度" :label-width="formLabelWidth" prop="idle_item_degree">
                            <el-select v-model="form.idle_item_degree" placeholder="选择闲置物品新旧程度...">
                              <el-option label="全新" value="1"></el-option>
                              <el-option label="9成新" value="2"></el-option>
                              <el-option label="5成新" value="3"></el-option>
                              <el-option label="使用过" value="4"></el-option>
                              <el-option label="破旧点" value="5"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>

                        <el-col :span="10">
                          <el-form-item label="闲置物品价格" :label-width="formLabelWidth" prop="idle_item_price" required>
                            <el-input-number v-model="form.idle_item_price" :precision="2" :step="0.1" :max="500"></el-input-number>
                          </el-form-item>
                        </el-col>

                      </el-row>

                      <el-form-item label="闲置物品描述" :label-width="formLabelWidth" prop="idle_item_info" >
                        <el-input
                            show-word-limit
                            type="textarea"
                            maxlength="300"
                            :rows="4"
                            placeholder="请输入描述，1-300个字符"
                            v-model="form.idle_item_info">
                        </el-input>
                      </el-form-item>

                      <el-form-item label="闲置物品图片" :label-width="formLabelWidth"
                                    style="text-align: justify;"
                                    prop="idle_item_img">

                        <el-upload ref="upload"
                                   name="upload"
                                   action="#"
                                   drag
                                   :file-list="fileList"
                                   list-type="picture"
                                   :limit="1"
                                   :on-exceed="handleExceed"
                                   :auto-upload="false"
                                   :on-remove="handleRemove"
                                   :on-change="imgChange">
                          <i class="el-icon-upload"></i>
                          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>

                      </el-form-item>

                      <el-form-item>
                        <el-button type="primary" @click="submitForm('form')">发 布</el-button>
                        <el-button @click="resetForm('form')">重置</el-button>
                        <el-button @click="cancel()">取 消</el-button>
                      </el-form-item>

                    </el-form>

                  </el-dialog>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--    底部导航条-->
    <myfooter></myfooter>
  </div>
</template>

<script>
import myfooter from '../../myfooter'
import navheader from '../../navheader'
import {getUser_Basic} from '@/api/User'

export default {
  name: "resale_main",
  components:{
    myfooter,
    navheader
  },
  data(){
    return {
      //若审核通过为1，可以发表评论，发表闲置物品信息
      activeIndex: '1',
      user_info:{
        user_id:'',
        user_name:'',
        identity:'',
        ifcheck:'',
        img:''
      },
      show_user_img:'',
      // dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        idle_item_name: '',
        idle_item_price: '',
        idle_item_degree: '',
        idle_item_category: '',
        idle_item_subject:'',
        idle_item_info:'',
        idle_item_img:''

      },
      //表单校验规则
      rules: {
       idle_item_name: [
          { required: true, message: '请输入闲置物品名称', trigger: 'blur'},
          { min:3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
       idle_item_price: [
          {type:"number", min:0,max:500,required: true, message: '请输入正确的闲置物品价格', trigger: 'blur'}
        ],
       idle_item_degree: [
          { required: true, message: '请选择闲置物品新旧程度', trigger: 'change'}
        ],
       idle_item_category: [
          {required: true, message: '请选择闲置物品类别', trigger: 'change'}
        ],
       idle_item_subject: [
          { required: true, message: '请选择闲置物品科目', trigger: 'change'}
        ],
       idle_item_info: [
          { min:1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur'}
        ],

      },
      formLabelWidth: '120px',
      fileList:[],
      file:[],
      if_img:0,


    }
  },
  methods:{
    //跳转
    change_user(){
      if(this.$router.history.current.path !='/Personal/Person_Idle'){
        this.$router.push({path:'/Personal/Person_Idle'});
      }
    },
    // 获取当前用户个人信息
    init(){

      getUser_Basic({
        // token:window.sessionStorage.getItem('token')
      }).then(res=>{

        this.user_info.user_id=res.data.user_id;
        this.user_info.user_name=res.data.username;
        this.user_info.ifcheck=res.data.ifcheck;
        this.user_info.img=res.data.img;
        this.user_info.identity=res.data.identity;
        this.show_user_img='/api/storage/user_img/' + this.user_info.img;

      });


    },
    openSubmit(){

      if(this.user_info.ifcheck!=1){

        this.$msg.error("未通过身份审核不可发布！");
        return false;
      }
      else{
        this.dialogFormVisible=true;
      }

    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
  //  清空发布的弹窗的内容 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$refs.upload.clearFiles();
      this.fileList=[];
    },
    //添加数据  发布闲置物品信息
    addSave()
    {

      let formData = new FormData();
      // alert(this.fileList.length);
      //没有上传图片
      if(this.fileList.length==0){
        formData.append('if_img',0);
        this.if_img=0;
      }
      //上传了图片
      else {
        formData.append('if_img',1);
        formData.append('idle_img', this.fileList[0].raw);
        this.if_img=1;
      }

      formData.append('user_token', window.sessionStorage.getItem('token'));
      formData.append('idle_item_name',this.form.idle_item_name);
      formData.append('idle_item_price',this.form.idle_item_price);
      formData.append('idle_item_category',this.form.idle_item_category);
      formData.append('idle_item_degree',this.form.idle_item_degree);
      formData.append('idle_item_subject',this.form.idle_item_subject);
      formData.append('idle_item_info',this.form.idle_item_info);

      // console.log(formData);

      this.$ajax({
        url: "/api/idle/addIdle",
        method: "post",
        dataType:'text',
        cache:  false , //上传文件无需缓存
        processData:  false , //用于对data参数进行序列化处理 这里必须false
        contentType:  false ,  //
        data:formData
      }).then((res)=>{

          if (res.data.code == 1) {
            this.$msg.success("发布成功，等待管理员审核！");
          }
          else {
            this.$msg.error('发布失败！');
          }
      });

      this.$refs.upload.clearFiles();
      this.dialogFormVisible=false;
      this.init();


    },
  //发布
    submitForm(formName) {
      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("发布失败！");
          });

        } else {
          this.$msg.error("发布失败！");
          return false;
        }
      });
    },
  //  关闭弹窗
    cancel() {
      this.dialogFormVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
      this.$refs.upload.clearFiles();
    },
    // 右上角 × 取消按钮
    closeDiv() {
      this.$refs.upload.clearFiles();
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
      this.$refs.upload.clearFiles();
    },
  //  文件上传相关
  // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      fileList=[];
      fileList.length=0;
      this.$refs.upload.clearFiles();
    },
    //  点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //限制上传数量
    handleExceed (file, fileList) {
      this.$msg.warning('只能上传一张图片！');
    },
    //限制用户上传的图片格式和大小。
    imgChange (file,fileList) {

      this.fileList = fileList;
      var img_type = file.name.substring(file.name.lastIndexOf('.') + 1)
      var imgSize = file.size;
      var img_maxsize = 1024 * 500;

      // console.log(img_type == 'jpg');

      if ((img_type != 'jpg') && (img_type != 'png') && (img_type != 'JPG') && (img_type != 'JPEG') && (img_type != 'jpeg')) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片只能是JPG或PNG或JPEG格式!');
        return false;
      }

      if (imgSize>img_maxsize) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片大小不能超过500KB!');
        return false;
      }

      return true;
      //this.$refs.uploadElement.clearValidate();

    },
    openDeal(){
      if (this.$router.history.current.path != '/Deal_Main/My_Buy_Deals') {
        this.$router.push({path: '/Deal_Main/My_Buy_Deals'});
      }
    },


  },
  created() {

    if(this.$router.history.current.path !='/Resale/All_Resale')
    {
      this.$router.push({path:'/Resale/All_Resale'})
    }

    let _this=this;

    _this.init();
  },

}
</script>

<style scoped>
.card{
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
</style>
